﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class TestLesson4
{
    public string name;
    public int age;
    public SerizlizerDictionary<int, string> dics;
    public TestLesson4()
    {
        name = "kitty";
        age = 18;
        dics = new SerizlizerDictionary<int, string>() {
            { 10, "小红"},
            { 20, "小明"},
            { 30, "小张"},
        };
    }
}

public class Lesson4 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        #region 知识点一 思考如何让Dictionary支持xml序列和反序列化
        //1.我们没办法修改C#自带的类
        //2.那我们可以重写一个类继承Dictionary然后让这个类继承序列化拓展接口IxmlSerializable
        //3.实现里面的序列化和反序列化方法即可
        #endregion

        #region 知识点二 让Dictionary支持序列化和反序列化

        TestLesson4 test = new TestLesson4();
        string path = Application.persistentDataPath + "/SerizlizerDictionary.xml";
        Debug.Log(path);
        //序列化
        using (StreamWriter write = new StreamWriter(path))
        {
            //序列化翻译机器 
            XmlSerializer s = new XmlSerializer(typeof(TestLesson4));
            //在序列化时 如果对象中的引用成员为空 那么xml里面是看不到字段的
            s.Serialize(write, test);
        }

        //反序列化
        using (StreamReader reader = new StreamReader(path))
        {
            XmlSerializer s = new XmlSerializer(typeof(TestLesson4));
            TestLesson4 data = s.Deserialize(reader) as TestLesson4;
        }
        #endregion
    }
}
